﻿//************************************************************************************************************
// CoNatural.Data.dll
// Author: Roger Torres
//************************************************************************************************************
// You can use, modify, and distribute the source code and executable programs based on the source code.
// This source code is provided "as is" and without warranties as to performance or merchantability. 
// The author and/or distributors of this source code may have made statements about this source code. 
// Any such statements do not constitute warranties and shall not be relied on by the user in deciding 
// whether to use this source code. This source code is provided without any express or implied warranties 
// whatsoever. Because of the diversity of conditions and hardware under which this source code may be used, 
// no warranty of fitness for a particular purpose is offered. The user is advised to test the source code 
// thoroughly before relying on it. The user must assume the entire risk of using the source code.
//************************************************************************************************************

using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Text;

namespace CoNatural.Data {
   /// <summary>
   /// Loads command's sql script from embedded resource file associated with iCommand
   /// </summary>
   public class EmbeddedResourceCommandScriptProviderBase : ICommandScriptProvider {
		private Dictionary<Type, string> scriptCache = new Dictionary<Type, string>();

      #region ICommandScriptProvider Members

      public string GetScript(ICommand iCommand) {
			// Load script from embedded resource file associated with ICommand
			Type type = iCommand.GetType();
			string script = null;
			lock (this) {
				if (!scriptCache.TryGetValue(type, out script)) {
					// SQL script embedded resources should match command's name with .sql extension
					string scriptName = type.FullName + ".sql";

					Stream stream = type.Assembly.GetManifestResourceStream(scriptName);
					if (stream == null)
						throw new Exception(string.Format("SQL script embedded resource for command {0} not found.", scriptName));

					using (stream) {
						byte[] data = new byte[stream.Length];
						stream.Read(data, 0, (int)stream.Length);
						script = Encoding.UTF8.GetString(data).Trim();
					}

					// save in cache
					scriptCache.Add(type, script);
				}
			}
			return script;
      }

		#endregion
	}

   /// <summary>
	/// Default script provider 
   /// </summary>
   public class DefaultCommandScriptProvider : ICommandScriptProvider {
      #region ICommandScriptProvider Members

      public string GetScript(ICommand iCommand) {
         return iCommand.GetScript();
      }

      #endregion
   }
}
